import pymysql
import pymssql
import _mssql
import uuid
import decimal

from bsf.log import *


class Conn:

    def __enter__(self):
        return self

    def __exit__(self, exception_type, exception_value, traceback):
        if exception_type is not None:
            print("数据库错误" + exception_type)
        if exception_value is not None:
            ErrorLog.writeln("数据库错误", exception_value, self.__class__)
        self.close()
        return True

    def __init__(self, dbtype, host, port, user, password, db):
        self._open(dbtype, host, port, user, password, db)

    def _open(self, dbtype, host, port, user, password, db):
        if dbtype == 'sqlserver':
            self._conn = pymssql.connect(host, port, user, password, db)
        else:
            self._conn = pymysql.connect(host, port, user, password, db)
        self._cursor = self.conn.cursor()

    def query(self, sql, params):
        self._cursor.execute(sql, params)
        return self._cursor.fetchall()

    def execute(self, sql, params):
        return self._cursor.execute(sql, params)

    def rollback(self):
        self._conn.rollback()

    def close(self):
        exp = None;
        if self._conn is not None:
          try:
              self._conn.commit()
          except Exception as e:
              exp = e
        if self._cursor is not None:
           try: self._cursor.close()
           except Exception as e:
               exp=e
        if self._conn is not None:
           try:  self._conn.close()
           except Exception as e:
                exp=e
        if exp is not None:
            raise exp




